<template>
  <div class="app-container">
    <ProTable
      :columns.sync="columns"
      :showSearch.sync="showSearch"
      :getList="getList"
      :loading="loading"
      :resetQuery="resetQuery"
      :tableData="tableData"
    >
      <template #pagination>
        <pagination
          v-show="total > 0"
          :total="total"
          :page-sizes="[10, 20, 50, 100, 200, 300, 500]"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </template>
      <template #form>
        <el-form :model="queryParams" ref="queryForm" size="small">
          <el-row>
            <el-form-item prop="name">
              <el-input
                :placeholder="$t('批次名')"
                clearable
                v-model="queryParams.name"
                @keyup.enter.native="getList"
              />
            </el-form-item>

            <el-form-item prop="status">
              <el-select clearable filterable @change="getList" :placeholder="$t('状态')" v-model="queryParams.status">
                <!-- 1 待配送 2 配送中 3 已完成 -->
                <el-option :label="$t('待配送')" value="1" />
                <el-option :label="$t('配送中')" value="2" />
                <el-option :label="$t('已完成')" value="3" />
              </el-select>
            </el-form-item>
          </el-row>
        </el-form>
      </template>
      <template #actions>
        <el-button
          @click="handleCreateBatch"
          plain
          size="mini"
          type="primary"
          v-hasPermi="['distribution:googleRouteBatch:add']"
        >
          {{ $t('创建批次') }}
        </el-button>
        <el-button @click="handleMyDispath" plain size="mini" type="success">
          {{ $t('我的派送任务') }}
        </el-button>
      </template>
      <template #completeNum="{ row }">
        <div class="_progress">
          <div style="flex: 1">
            <el-progress text-inside :stroke-width="15" :percentage="handlePercentage(row)" />
          </div>
          <div class="_text">{{ row.completeNum }} / {{ row.num || 0 }}</div>
        </div>
      </template>
      <template #status="{ row }">
        <!-- 1待配送 2配送中 3已完成 -->
        <div v-if="row.status == 1" :style="{ color: $randomColor(row.status) }">{{ $t('待配送') }}</div>
        <div v-if="row.status == 2" :style="{ color: $randomColor(row.status) }">{{ $t('配送中') }}</div>
        <div v-if="row.status == 3" :style="{ color: $randomColor(row.status) }">{{ $t('已完成') }}</div>
      </template>
      <template #option="{ row }">
        <el-dropdown @command="(command) => handleCommand(command, row)">
          <span class="el-dropdown-link">
            {{ $t('更多') }}
            <i class="el-icon-arrow-down"></i>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item v-hasPermi="['distribution:googleRoute:list']" command="handleViewBatch">
              {{ $t('查看批次') }}
            </el-dropdown-item>
            <el-dropdown-item
              v-hasPermi="['distribution:googleRouteBatch:getRouteBatchInfo']"
              command="handleEditBatch"
              :disabled="row.status != 1"
            >
              {{ $t('修改批次') }}
            </el-dropdown-item>
            <!-- 1待配送 2配送中 3已完成  1待配送才能导入包裹 -->
            <el-dropdown-item
              v-hasPermi="['distribution:googleRouteBatch:importPackageByRoute']"
              command="handleImportPackage"
              :disabled="row.status != 1"
            >
              {{ $t('导入包裹') }}
            </el-dropdown-item>
            <el-dropdown-item
              v-hasPermi="['distribution:googleRouteBatch:printShipments']"
              command="handlePrintShipments"
            >
              {{ $t('打印面单') }}
            </el-dropdown-item>
            <el-dropdown-item
              v-hasPermi="['distribution:googleRouteBatch:startShipment']"
              command="handleStartDispatch"
              :disabled="row.status != 1"
            >
              {{ $t('开始配送') }}
            </el-dropdown-item>
            <el-dropdown-item
              :disabled="row.status != 1"
              v-hasPermi="['distribution:googleRouteBatch:remove']"
              command="handleDelete"
            >
              {{ $t('删除批次') }}
            </el-dropdown-item>

            <el-dropdown-item
              :disabled="row.status != 1"
              v-hasPermi="['distribution:googleRouteBatch:chooseOrderBatchImport']"
              command="handleSelectPackageImport"
            >
              {{ $t('选择包裹导入') }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </template>
    </ProTable>

    <!-- sku弹窗 -->
    <Skucontmoduler @relaod="relaod" ref="Skucontmoduler"></Skucontmoduler>

    <!-- 打印面单 -->
    <Print :show.sync="print.show" :formData="print.formData" @getList="getList" />
    <!-- 查看批次 -->
    <ViewBatch :show.sync="viewBatch.show" :formData="viewBatch.formData" @getList="getList" />
    <!-- 修改批次 -->
    <EditBatch :show.sync="editBatch.show" :formData="editBatch.formData" @getList="getList" />
    <!-- 创建批次 -->
    <CreateBatch :show.sync="createBatch.show" :formData="createBatch.formData" @getList="getList" />
    <!-- 导入包裹 -->
    <ImportPackage :show.sync="importPackage.show" :formData="importPackage.formData" @getList="getList" />
    <!-- 选择路线查询 -->
    <SelectRoute :show.sync="selectRoute.show" :routes="selectRoute.routes" />
    <!-- 选择包裹导入 -->
    <SelectPackageImport
      :show.sync="selectPackageImport.show"
      :formData="selectPackageImport.formData"
      @getList="getList"
    />
  </div>
</template>

<script>
import {
  printShipments,
  googleRouteBatchList,
  deleteGoogleRouteBatch,
  startShipment,
} from '@/api/orderManage/batchDispatch'
import { myUnCompleteList } from '@/api/orderManage/myDispatch'

import { Loading } from 'element-ui'
import ViewBatch from './components/viewBatch.vue'
import EditBatch from './components/editBatch/index.vue'
import CreateBatch from './components/createBatch.vue'
import SelectRoute from './components/selectRoute.vue'
import ImportPackage from './components/importPackage.vue'
import SelectPackageImport from './components/selectPackageImport.vue'
import Print from './components/print.vue'

export default {
  components: { Print, ViewBatch, EditBatch, CreateBatch, SelectRoute, ImportPackage, SelectPackageImport },
  data() {
    return {
      /**选择包裹导入 */
      selectPackageImport: {
        show: false,
        formData: {},
      },
      /**选择路线查询 */
      selectRoute: {
        show: false,
        routes: [],
      },
      /**打印面单 */
      print: {
        show: false,
        formData: {},
      },
      /**导入包裹 */
      importPackage: {
        show: false,
        formData: {},
      },
      /**创建批次 */
      createBatch: {
        show: false,
        formData: {},
      },
      /**修改批次 */
      editBatch: {
        show: false,
        formData: {},
      },
      /**查看批次 */
      viewBatch: {
        show: false,
        formData: {},
      },
      /**@type {ProTableColumns}*/
      columns: [
        { label: '批次名', prop: 'name' },
        { label: '创建日期', prop: 'createTime' },
        { label: '完成数/包裹数', prop: 'completeNum', useSlot: true, width: 220 },
        { label: '车辆', prop: 'vehiclesNum' },
        { label: '路线优化次数', prop: 'optimizationNum' },
        { label: '总时长/h', prop: 'totalTime' },
        { label: '状态', prop: 'status', useSlot: true },
        // <!-- strategyPattern	策略模式 1-自动分配 2-平均分配 -->
        {
          label: '策略',
          prop: 'strategyType',
          formatter: (v) => {
            if (v == 1) return '自动分配'
            if (v == 2) return '平均分配'
          },
        },
        { label: '操作', prop: 'option', fixed: 'right', useSlot: true },
      ],
      /**字典数据 */
      dict_type_list: [],
      /**显示搜索*/
      showSearch: false,
      /**表格数据 */
      tableData: [],

      /**数据总条数 */
      total: 0,
      /**表格加载状态 */
      loading: false,
      /**
       * @type {import('element-ui/types/loading').ElLoadingComponent}
       */
      loadingInstance: null,
      /**查询参数 */
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        xx2: '',
      },
    }
  },
  created() {
    this.getList()
    this.getDictList()
  },
  methods: {
    handlePercentage(row) {
      const p = +((row.completeNum / row.num) * 100).toFixed()
      if (isNaN(p)) return 0
      return p
    },
    formatProgress(percentage) {
      return percentage == 100 ? '已完成' : `${percentage}%`
    },
    /**选择包裹导入 */
    handleSelectPackageImport(row) {
      this.selectPackageImport.formData = { ...row }
      this.selectPackageImport.show = true
    },
    handlePrintShipments(row) {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)',
      })
      const data = {
        batchId: row.id,
      }
      printShipments(data)
        .then(async (res) => {
          const data = res.data.batchPackage
          data[data.length - 1].isLast = true
          for (let index = 0; index < data.length; index++) {
            data[index].packageNoSrc = await this.createQRCode({
              width: 100,
              height: 100,
              text: data[index].packageNo,
            })
            data[index].packageNoSrc2 = await this.createQRCode({
              width: 83,
              height: 83,
              text: data[index].packageNo,
            })
            data[index].linkSrc = await this.createQRCode({
              width: 100,
              height: 100,
              text: data[index].link,
            })
          }

          this.print.formData = data
          this.print.show = true
        })
        .finally(() => loading.close())
    },
    /**导入包裹 */
    handleImportPackage(row) {
      this.importPackage.formData = { ...row }
      this.importPackage.show = true
    },
    handleMyDispath() {
      myUnCompleteList().then((res) => {
        const { rows, total } = res
        if (total == 0) return this.$message({ type: 'error', message: this.$t('暂无派送任务') })
        if (total == 1) {
          const router = this.$router.resolve({
            path: '/googleMap',
            query: {
              routeId: rows[0].id,
            },
          })
          window.location.href = router.href
        }
        if (total > 1) {
          this.selectRoute.show = true
          this.selectRoute.routes = rows
        }
      })
    },
    /**修改批次 */
    handleEditBatch(row) {
      this.editBatch.formData = { ...row }
      this.editBatch.show = true
    },
    /**查看批次 */
    handleViewBatch(row) {
      this.viewBatch.formData = { ...row }
      this.viewBatch.show = true
    },
    /**确认开始配送 */
    handleStartDispatch(row) {
      this.$confirm(this.$t('开始配送后不能更改包裹和行程,确认开始配送?'), this.$t('提示'), {
        type: 'warning',
      }).then(() => {
        const data = {
          id: row.id,
        }
        startShipment(data).then((res) => {
          const { code, data, msg } = res
          if (code === 200) {
            this.$message({ type: 'success', message: msg })
            this.getList()
          }
        })
      })
    },

    /**获取字典数据 */
    getDictList() {
      // this.useDict('dict_type').then(({ dict_type }) => (this.dict_type_list = dict_type))
    },
    handleCommand(command, row) {
      this[command](row)
    },

    handleCreateBatch() {
      this.createBatch.formData = {}
      this.createBatch.show = true
    },

    handleDelete(row) {
      this.$confirm(this.$t(`确认删除批次${row.name}?`), this.$t('提示'), {
        type: 'warning',
      })
        .then(() => {
          deleteGoogleRouteBatch(row.id).then((res) => {
            if (res.code == 200) {
              this.$message({ type: 'success', message: res.msg })
              this.getList()
            }
          })
        })
        .catch((e) => e)
    },
    startLoading() {
      this.loadingInstance = Loading.service({
        text: 'Loading...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)',
      })
    },
    endLoading() {
      this.loadingInstance?.close()
    },
    relaod() {
      this.getList()
    },
    /** 查询菜单列表 */
    getList() {
      this.loading = true
      googleRouteBatchList(this.queryParams)
        .then((res) => {
          this.tableData = res.rows
          this.total = res.total
        })
        .finally(() => (this.loading = false))
    },
    /** 重置按钮操作 */
    resetQuery() {
      Object.keys(this.queryParams).forEach((key) => (this.queryParams[key] = null))
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.getList()
    },
  },
}
</script>
<style scoped lang="scss">
._progress {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 3px;
  ._text {
    width: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
